package com.sunday.android.fangdaifu.bukong.fragment.tab;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.sunday.android.fangdaifu.bukong.BaseApp;
import com.sunday.android.fangdaifu.bukong.R;
import com.sunday.android.fangdaifu.bukong.adapter.NewsListAdapter;
import com.sunday.android.fangdaifu.bukong.entity.NewsItem;
import com.sunday.android.fangdaifu.bukong.http.ApiClient;
import com.sunday.android.fangdaifu.bukong.utils.LazyFragment;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.EmptyLayout;
import com.sunday.member.base.BaseFragment;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by yun_sheng on 2017/6/29.
 */

public class NewsItemFragment extends LazyFragment {

    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;
    @Bind(R.id.emptylayout)
    EmptyLayout emptylayout;
    @Bind(R.id.refresh_layout)
    SwipeRefreshLayout refreshLayout;

    private NewsListAdapter adapter;
    private LinearLayoutManager layoutManager;

    private long id,memberId;
    private boolean isPrepared;
    private boolean mHasLoadedOnce;

    private List<NewsItem> newsItemList = new ArrayList<>();
    private List<NewsItem> imgItemList = new ArrayList<>();

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.item_fragment_news, container, false);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        id = getArguments().getLong("id");
        memberId = BaseApp.getInstance().getMemberId();
        initView();
        isPrepared = true;
        lazyLoad();
    }

    private void initView() {
        refreshLayout.setColorSchemeResources(R.color.material_red, R.color.material_green,
                R.color.material_blue, R.color.material_yellow);
        adapter = new NewsListAdapter(mContext,newsItemList,imgItemList);
        layoutManager = new LinearLayoutManager(mContext,LinearLayoutManager.VERTICAL,false);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                pageNo=1;
                getData();
                getImageData();
            }
        });
    }

    @Override
    protected void lazyLoad() {
        if (!isPrepared || !isVisible || mHasLoadedOnce) {
            return;
        }
        mHasLoadedOnce = true;
        loading();
        getData();
        getImageData();
        handleRecycle();
    }

    private void loading(){
        if (!refreshLayout.isRefreshing()){
            refreshLayout.setRefreshing(true);
        }
    }

    private void getData(){
        Call<ResultDO<List<NewsItem>>> call = ApiClient.getApiAdapter().list(id,pageNo,pageSize);
        call.enqueue(new Callback<ResultDO<List<NewsItem>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<NewsItem>>> call, Response<ResultDO<List<NewsItem>>> response) {
                if (response.body() == null || isFinish) {
                    return;
                }
                refreshLayout.setRefreshing(false);
                if (response.body().getCode() == 0 && response.body().getResult() != null) {
                    newsItemList.clear();
                    newsItemList.addAll(response.body().getResult());
                    setEmpty();
                    adapter.notifyDataSetChanged();
                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<NewsItem>>> call, Throwable t) {
                if (isFinish) {
                    return;
                }
                refreshLayout.setRefreshing(false);
            }
        });
    }

    private void getImageData(){
        Call<ResultDO<List<NewsItem>>> call = ApiClient.getApiAdapter().show(id);
        call.enqueue(new Callback<ResultDO<List<NewsItem>>>() {
            @Override
            public void onResponse(Call<ResultDO<List<NewsItem>>> call, Response<ResultDO<List<NewsItem>>> response) {
                if (response.body() == null || isFinish) {
                    return;
                }
                refreshLayout.setRefreshing(false);
                if (response.body().getCode() == 0 && response.body().getResult() != null) {
                    imgItemList.clear();
                    imgItemList.addAll(response.body().getResult());
                    setEmpty();
                    adapter.notifyDataSetChanged();
                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO<List<NewsItem>>> call, Throwable t) {
                if (isFinish) {
                    return;
                }
                refreshLayout.setRefreshing(false);
            }
        });
    }

    private void setEmpty(){
        if (imgItemList.size()==0 && newsItemList.size()==0){
            emptylayout.setErrorType(EmptyLayout.NODATA);
        }else {
            emptylayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
        }
    }

    private int pageNo = 1, pageSize = 10;
    private boolean isCanloadMore = false;
    private int lastVisibleItem;

    private void handleRecycle() {
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                pageNo = 1;
                getData();
            }
        });
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE &&
                        lastVisibleItem + 1 == adapter.getItemCount() && isCanloadMore) {
                    pageNo++;
                    getData();
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = layoutManager.findLastVisibleItemPosition();
                isCanloadMore = dy > 0;
            }
        });
    }

    public static NewsItemFragment newInstance(long id) {
        NewsItemFragment fragment = new NewsItemFragment();
        Bundle bundle = new Bundle();
        bundle.putLong("id", id);
        fragment.setArguments(bundle);
        return fragment;
    }

}
